package com.saodisheng.config;

import com.saodisheng.realm.UserRealm;
import com.saodisheng.constant.Constant;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * description:
 * shiro配置类
 *
 * @author 扫地生_saodisheng
 * @date 2021/12/30
 */
@Configuration
public class ShiroConfiguration {
    @Bean
    public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    /**
     * 创建ShiroFilterFactoryBean
     *
     * @author saodisheng_liuxingwu
     * @modifyDate 2021/12/30
    */
    @Bean
    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        return shiroFilterFactoryBean;
    }

    /**
     * 创建SecurityManager
     *
     * @author saodisheng_liuxingwu
     * @modifyDate 2021/12/30
    */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 关联realm对象
        securityManager.setRealm(getUserRealm());
        return securityManager;
    }

    /**
     * 注入realm对象
     *
     * @author saodisheng_liuxingwu
     * @modifyDate 2021/12/30
    */
    @Bean
    public UserRealm getUserRealm() {
        UserRealm saodishengShiroRealm = new UserRealm();
        saodishengShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return saodishengShiroRealm;
    }

    /**
     * 哈希加密匹配器
     *
     * @author saodisheng_liuxingwu
     * @modifyDate 2021/12/30
    */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName(Constant.ENCODE_ALGROITHM);
        hashedCredentialsMatcher.setHashIterations(Constant.ENCODE_TIMES);
        return hashedCredentialsMatcher;
    }

    /**
     * 开启shiro aop注解支持.
     * 使用代理方式;所以需要开启代码支持;
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
}
